import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type MessageParamsWithType,
} from "element-plus";
import { ref, reactive, getCurrentInstance } from "vue";
import { useReg } from "../RegExp/useReg";

export function useRegist() {
  // const { userInfos } = useStore()
  const flag = ref(false);
  //正则验证
  const {
    validateUser,
    validatePass,
    validateSex,
    validateBir,
    validatePhone,
    validateAddress,
  } = useReg();
  const registeRuleFormRef = ref<FormInstance>();
  const { proxy }: any = getCurrentInstance();
  const regisForm = ref<any>({
    userName: "",
    userPass: "",
    userSex: "",
    birthday: "",
    phone: "",
    address: "",
    avater:
      "https://img0.baidu.com/it/u=1561984098,4261095823&fm=253&fmt=auto&app=138&f=JPEG?w=513&h=339",
  });

  const registRules = reactive<FormRules>({
    userName: [{ validator: validateUser, trigger: "blur" }],
    userPass: [{ validator: validatePass, trigger: "blur" }],
    userSex: [{ validator: validateSex, trigger: "blur" }],
    birthday: [{ validator: validateBir, trigger: "blur" }],
    phone: [{ validator: validatePhone, trigger: "blur" }],
    address: [{ validator: validateAddress, trigger: "blur" }],
  });

  //普通用户提交注册表单
  const subRegiste = async (regist: FormInstance | undefined) => {
    if (!regist) return;
    await regist.validate((valid) => {
      if (!valid) return;
      proxy.$http
        .post("/user/register", {
          userName: regisForm.value.userName,
          userPass: regisForm.value.userPass,
          userSex: regisForm.value.userSex,
          birthday: regisForm.value.birthday,
          phone: regisForm.value.phone,
          address: regisForm.value.address,
          avater: regisForm.value.avater,
        })
        .then((res: any) => {
          ElMessage.success(res.message);
          flag.value = !flag.value;
          regisForm.value = ''
        })
        .catch((err: any) => {
          ElMessage.error(err.response.data.message);
        });
    });
  };

  //重置表单
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }

  return {
    registeRuleFormRef,
    registRules,
    regisForm,
    subRegiste,
    flag,
    resetForm,
  };
}
